package com.gagan.tplmatcher;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gagan.goku@gmail.com
 */
public class StringPattern {
  private final String pattern;
  private final int patternIdx;

  public StringPattern(String pattern, int patternIdx) {
    this.pattern = pattern;
    this.patternIdx = patternIdx;
  }

  public String getPattern() {
    return pattern;
  }

  public List<List<MatchResult>> apply(String html) {
    String p = pattern;
    Pattern pattern = Pattern.compile(p, Pattern.DOTALL | Pattern.MULTILINE |
                                         Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(html);

    List<List<MatchResult>> allMatches = new ArrayList<List<MatchResult>>();

    boolean found = true;
    while (found) {
      found = matcher.find();

      if (found) {
        // Get all groups for this match, with first one being the complete match.
        List<MatchResult> matches = new ArrayList<MatchResult>();

        for (int i = 0; i <= matcher.groupCount(); i++) {
          matches.add(new MatchResult(matcher.start(i), matcher.end(i), html, patternIdx));
        }

        allMatches.add(matches);
      }
    }

    return allMatches;
  }
}
